<template>
  <div class="export-records-container">
    <div class="page-header">
      <div class="header-content">
        <h2>{{ t('exportRecords.title') }}</h2>
        <el-button type="primary" @click="goToPersonalCenter">
          <el-icon><Back /></el-icon>
          返回个人中心
        </el-button>
      </div>
    </div>
    
    <div class="records-table-container">
      <el-table
        v-loading="loading"
        :data="records"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column
          prop="fileName"
          :label="t('exportRecords.fileName')"
          min-width="180"
          show-overflow-tooltip
        />
        
        <el-table-column
          prop="dataSource"
          :label="t('exportRecords.dataSource')"
          min-width="120"
        >
          <template #default="scope">
            <el-tag :type="getDataSourceTag(scope.row.dataSource)">
              {{ getDataSourceName(scope.row.dataSource) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="fileSize"
          :label="t('exportRecords.fileSize')"
          min-width="100"
        />
        
        <el-table-column
          prop="records"
          :label="t('exportRecords.recordCount')"
          min-width="100"
        />
        
        <el-table-column
          prop="exportDate"
          :label="t('exportRecords.exportDate')"
          min-width="160"
          :formatter="formatDate"
        />
        
        <el-table-column
          :label="t('exportRecords.actions')"
          min-width="100"
        >
          <template #default="scope">
            <el-tooltip content="文件下载功能暂未启用" placement="top">
              <el-button
                size="small"
                type="info"
                link
                disabled
              >
                {{ t('exportRecords.download') }}
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <div v-if="records.length === 0 && !loading" class="empty-records">
      <el-empty :description="t('exportRecords.noRecords')" />
    </div>
    
    <div class="notice-message">
      <el-alert
        title="文件下载功能暂未启用，导出记录仅用于查看历史导出信息"
        type="info"
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getExportRecords, downloadExportFile } from '@/api/export';
import { t } from '@/utils/i18n';
import { useRouter } from 'vue-router';
import { Back } from '@element-plus/icons-vue';

const router = useRouter();

// 状态变量
const records = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

// 获取导出记录列表
const fetchRecords = async () => {
  loading.value = true;
  try {
    const response = await getExportRecords({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    
    if (response && response.data) {
      records.value = response.data.records || [];
      // 为每条记录添加下载状态
      records.value.forEach(record => {
        record.downloading = false;
      });
      totalRecords.value = response.data.total || 0;
    }
  } catch (error) {
    ElMessage.error(t('exportRecords.downloadFailed'));
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (row, column) => {
  const date = new Date(row.exportDate);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 根据数据来源获取对应的Tag类型
const getDataSourceTag = (dataSource) => {
  const tagMap = {
    'customs-trade-info': 'success',
    'global-enterprise': 'primary',
    'canton-fair-purchasers': 'warning',
    'canton-fair-exhibitors': 'danger',
    'linkedin': 'info',
    'facebook': '',
    'twitter': ''
  };
  
  return tagMap[dataSource] || '';
};

// 根据数据来源获取显示名称
const getDataSourceName = (dataSource) => {
  const nameMap = {
    // 'customs-trade-info': '海关数据', // 海关数据 - 已注释掉
    'global-enterprise': '全球企业库',
    'canton-fair-purchasers': '广交会采购商',
    'canton-fair-exhibitors': '广交会参展商',
    'linkedin': 'LinkedIn',
    'facebook': 'Facebook',
    'twitter': 'Twitter'
  };

  return nameMap[dataSource] || dataSource;
};

// 处理文件下载
const downloadFile = async (record) => {
  try {
    // 设置下载状态
    record.downloading = true;
    
    // 发送下载请求
    const response = await downloadExportFile(record.id);
    
    // 处理下载逻辑
    if (response && response.data instanceof Blob) {
      // 创建Blob对象
      const blob = response.data;
      
      // 下载文件
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = record.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      ElMessage.success(t('exportRecords.downloadSuccess'));
    } else {
      throw new Error('下载失败：响应格式不正确');
    }
  } catch (error) {
    ElMessage.error(t('exportRecords.downloadFailed'));
  } finally {
    // 重置下载状态
    record.downloading = false;
  }
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchRecords();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchRecords();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchRecords();
});

// 跳转到个人中心
const goToPersonalCenter = () => {
  router.push('/personal-center');
};
</script>

<style scoped>
.export-records-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.records-table-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.empty-records {
  margin-top: 40px;
  text-align: center;
}

.notice-message {
  margin-top: 20px;
}
</style>